package js.dwim.server;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import js.dwim.domain.Player;
import js.dwim.domain.WorldMap;

public class Game
{
    public static WorldMap getWorldMap()
    {
        PersistenceManager pm		= Persistence.getManager();
        WorldMap world, detached    = null;

        try
        {
            Query q = pm.newQuery( WorldMap.class );

            @SuppressWarnings( "unchecked" )
            List<WorldMap> result = (List<WorldMap>) q.execute();
            if ( !result.isEmpty() )
            {
                world       = result.get( 0 );
                detached    = pm.detachCopy( world );
            }
            else
            {
                world 		= new WorldMap();
                detached 	= pm.detachCopy( pm.makePersistent( world ) );
            }
        }
        finally
        {
            pm.close();
        }
        return detached;
    }
    
    public static Player getAiPlayer()
    {
    	PersistenceManager pm 	= Persistence.getManager();
        Player player, detached = null;

        try
        {
            Query q = pm.newQuery( Player.class, "name == p_name" );
            q.declareParameters( "java.lang.String p_name" );
            
            @SuppressWarnings( "unchecked" )
            List<Player> result = (List<Player>) q.execute( Player.AI_PLAYER );
            if ( !result.isEmpty() )
            {
            	player      = result.get( 0 );
                detached    = pm.detachCopy( player );
            }
            else
            {
            	player 		= new Player( Player.AI_PLAYER );
                detached 	= pm.detachCopy( pm.makePersistent( player ) );
            }
        }
        finally
        {
            pm.close();
        }
        return detached;
    }
}
